import React from 'react';

import Header from '../common/Header';
import CKModal from '../components/CKModal';
import Validate from '../common/Validate';
import moment from 'moment';
import AMUIReact,{
    Button,
    Input,
    Form,
    Icon,
    Selected
} from 'amazeui-react';

import Fetch from '../common/Fetch';

import '../assets/css/manage/user_edit.less';

class User extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            data:{},
            groupData:[

            ],
            is_upload:false,
            upload_img:'',
            is_save:false,
            type:this.props.params.id ? 'edit':'add',
            init:false
        };
        this.file = null;
    }

    componentDidMount() {
        this.loadGroupData();
        if (this.state.type === 'edit') {
            this.loadData();
        }
    }

    loadGroupData() {
        this.refs.modal.load('正在加载数据...');
        Fetch('/res/group/get_list',{page:1,number:30},(res)=>{
            if (res.status) {
                var group = res.data.list.map((item)=>{
                    return {label:item.grp_name,value:item.grp_id};
                });

                this.setState({
                    groupData:group
                });
                this.refs.modal.closeModal();
            } else {
                this.refs.modal.alert('提示','加载用户组数据出错',()=>{
                    this.context.router.push('/user');
                    return true;
                });
            }
        },()=>{
            this.refs.modal.closeModal();
        });
    }

    loadData() {
        this.refs.modal.load('正在加载数据...');
        Fetch('/res/account/get_user',{id:this.props.params.id},(res)=>{
            if (res.status) {
                this.setState({
                    data:res.data
                });
                this.refs.modal.closeModal();
            } else {
                this.refs.modal.alert('提示','加载用户数据出错',()=>{
                    this.context.router.push('/user');
                    return true;
                });
            }
        },()=>{
            this.refs.modal.closeModal();
        });
    }

    changeHandler(field){
        return (e)=>{
            var info = this.state.data;
            info[field] = e.target.value;
            this.setState({data:info});
        }
    }

    saveUser = ()=>{
        var data = this.checkData();
        if (data === false) return;
        if (this.state.is_save) return;
        this.setState({
            is_save:true
        });
        this.refs.modal.load('正在保存数据...');
        Fetch('/res/account/save',data,(res)=>{
            if (res.status) {
                this.refs.modal.alert('成功','保存用户数据成功!',()=>{
                    this.context.router.push('/user');
                });
            } else {
                this.refs.modal.alert('失败','保存用户失败!!');
                this.setState({
                    is_save:false
                });
            }
        },()=>{
            this.refs.modal.alert('失败','远程调用失败!!');
            this.setState({
                is_save:false
            });
        });
    };

    checkData() {
        var valid = {
            'acc_username':{role:'s1-20',errmsg:'用户名为6到20个字符'},
            'acc_password':{role:'*6-20',option:this.state.type === 'edit',errmsg:'密码为6到30个任意字符'},
            'acc_name':{role:'s2-40',errmsg:'真实姓名为2到40的字符'},
            'grp_id':{role:'*',errmsg:'请选择用户组'},
            'acc_email':{role:'e',option:true,errmsg:'Email格式错误'}
        };
        var data = {};
        $.map(this.refs,(item,key)=>{
            if (/^acc/.test(key)) {
                let field = item.props.field || key;
                data[field] = item.getValue();
            }
        });
        if (this.state.type === 'edit') {
            data['acc_id'] = this.props.params.id;
        }
        if (this.state.upload_img !== '') {
            data['upload_file'] = this.state.upload_img;
        }
        data['grp_name'] = this.getGroupName(data['grp_id']);
        try {
            Validate.inst().checkData(data,valid);
            return data;
        } catch (e) {
            this.refs.modal.alert('错误',e);
            return false;
        }
    }

    getGroupName(value) {
        var name = '';
        this.state.groupData.forEach((item)=>{
            if (item.value === value) {
                name = item.label;
            }
        });
        return name;
    }

    validate() {

    }

    uploadHead = ()=>{
        if (!this.file) {
            var self = this;
            this.file = $('<input type="file"/>');
            this.file.on('change',function(e){
                self.refs.modal.load('正在读取图片...');
                lrz(this.files[0],{width:300,height:300,quality:.9})
                    .then((rst)=>{
                        $('#head_img').attr('src',rst.base64);
                        self.setState({
                            is_upload:true
                        });
                        self.refs.modal.load('正在上传图片...');
                        Fetch('/res/upload/base64_image',
                            {data:rst.base64},
                            (res)=>{
                                self.refs.modal.closeModal();
                                if (res.status) {
                                    self.setState({
                                        is_upload:false,
                                        upload_img:res.data
                                    });
                                }
                            }
                        );
                    })
                    .catch((err)=>{
                        self.refs.modal.closeModal('上传图片出错!:'+err);
                    }).always(()=>{
                        this.file.value = '';
                    });
            });
        }
        this.file.click();
    };

    render() {
        let data = this.state.data;
        return (
            <div className="content">
                <Header title={this.state.type === 'add' ? "新增用户":'修改用户'} back={true}/>
                <div className="content_main">
                    <div style={{marginBottom:'20px'}}>
                        <h4 className="title">用户信息</h4>
                    </div>
                    <Form ref="from" horizontal style={{marginTop:'20px'}}>
                        <div className="am-form-group">
                            <div className="am-u-sm-2">
                                &nbsp;
                            </div>
                            <div className="am-u-sm-4 am-u-end">
                                <img id="head_img" src={data.acc_head_img || require('../assets/img/default_head.jpg')} className="header_img"/>
                                <Button style={{marginLeft:'20px'}}
                                        amStyle="primary"
                                        disabled={this.state.is_upload}
                                        onClick={this.uploadHead}>

                                    {this.state.is_upload ? '上传中...' : '上传'}
                                </Button>
                            </div>
                        </div>
                        <Input ref="acc_username" label="登录名"
                               labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.acc_username || ''}
                               onChange={this.changeHandler('acc_username')}
                               vali="s6-20"
                               placeholder="登录名为6到20个字符"
                               valimsg="用户名为6-20个字母下划线组成"
                        />
                        <div className="am-form-group">
                            <label className="am-u-sm-2 am-form-label">
                                用户组
                            </label>
                            <div className="am-u-sm-4 am-u-end">
                                <Selected ref="acc_grp_id"
                                          field="grp_id"
                                          btnStyle="primary"
                                          placeholder="请选择用户组"
                                          data={this.state.groupData}
                                          value={data.grp_id || '1'}/>
                            </div>
                        </div>
                        <Input id="acc_password"
                               ref="acc_password"
                               label="密码"
                               labelClassName="am-u-sm-2"
                               type="password"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               placeholder={this.state.type == 'edit' ? '不填写则不修改' : '密码为6到30个任意字符'}
                        />
                        <Input id="acc_name" ref="acc_name" label="真实姓名" labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.acc_name}
                               placeholder="真实姓名为2到40的字符"
                               onChange={this.changeHandler('acc_name')}
                        />
                        <Input id="acc_email" ref="acc_email" label="Email" labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={data.acc_email}
                               placeholder="用户email"
                               onChange={this.changeHandler('acc_email')}
                        />
                        <Input label="创建时间" labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={moment.unix(data.created_date).format('YYYY-MM-DD HH:mm:ss')}
                               disabled
                        />
                        <Input label="修改时间" labelClassName="am-u-sm-2"
                               wrapperClassName="am-u-sm-4 am-u-end"
                               value={moment.unix(data.modified_date).format('YYYY-MM-DD HH:mm:ss')}
                               disabled
                        />
                    </Form>
                    <div className="am-form-group">
                        <div className="am-u-sm-2">
                            &nbsp;
                        </div>
                        <div className="am-u-sm-4 am-u-end">
                            <Button amStyle="primary"
                                    onClick={this.saveUser}
                                    disabled={this.state.is_save}
                            >
                                {this.state.is_save?'保存中...':'保存'}
                            </Button>
                        </div>
                    </div>
                </div>
                <CKModal ref="modal"/>
            </div>
        );
    }
}

User.contextTypes = {
    router: React.PropTypes.object
};

export default User;